package ordinaryArray;

import org.junit.Test;

/*
 *@description
 *@author hkfan
 *@version 1.0
 *@create 2025/5/26 17:02
 */
public class leetCode_134 {

    @Test
    public void test(){
        System.out.println(canCompleteCircuit(new int[]{5,8,2,8},new int[]{6,5,6,6}));
    }

    public int canCompleteCircuit(int[] gas, int[] cost) {
        //1. 计算cost数组
        for (int i = 0; i < cost.length; i++) {
            cost[i] = gas[i]-cost[i];
        }
        //2. 循环判断
        for (int i = 0; i < cost.length; ) {
            int j = check(cost,i);
            if (j<0){
                return i;
            } else if (j<=i) {
                return -1;
            }else {
                i=j;
            }
        }
        return -1;
    }

    private int check(int[] cost, int i) {
        int sum=0;
        for (int j = 0; j < cost.length; j++) {
            sum+=cost[i];
            if (sum<0){
                return (i+1)%cost.length;
            }
            i=(i+1)%cost.length;
        }
        return -1;
    }


}
